<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Application.Decorator
 * 
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
 /**
  * Decorator
  */
abstract class Decorator extends ApplicationController implements IViewable
{
    /**
     * Decorator name
     *
     * @var string
     */
	protected $name;
	
	/**
	 * IViewable
	 *
	 * @var IViewable
	 */
	protected $object;
	
	/**
	 * IView
	 *
	 * @var IView
	 */
	protected $view;
	
    public function __construct(IViewable $object)
    {
        $this->object = $object;
    	$this->view = Registry::get('View');
    	$this->name = str_replace('Decorator', '', get_class($this));
	}
	
	public function prepare()
	{
	   if($this->object instanceof ApplicationController) {
            $this->object->prepare();
        }
        
        if($this->object instanceof INeedsParentObject) {
            $this->object->setParent($this);
        }
        
        if($this->object instanceof IExecutable) {
            $this->object->exec();
        }
        
	    if($this->object instanceof IDecoratable) {
            $this->view->assign('title', $this->object->getTitle());
        }
	}
    
	/**
	 * Получить имя шаблона декоратора.
	 *
	 * @return string
	 */
    protected function getTemplateName()
    {
    	return "{$this->name}.tpl";
    }
    
    /**
     * Возвращает контент сгенерированный декоратором и контроллером.
     *
     * @return string
     */
    public function display()
    {
    	$content = '';
    	if($this->name) {
    		$content = $this->view->fetch($this->getTemplateName());
    	}
    	
    	return $content . $this->object->display();
    }
    
    /**
     * Возвращает декорируемый объект.
     *
     * @return IViewable
     */
    public function children()
    {
    	return $this->object;
    }
    
    /**
     * Get classname of current instance.
     *
     * @return string
     */
    public function getInstanceName()
    {
        return get_class($this);
    }
}

?>